//
//  HQMapManager.m
//  o_amap
//
//  Created by Q神 on 2021/4/6.
//

#import "HQMapManager.h"

#import "HQMapTools.h"
#import "MJExtension.h"
#import "HQMapPolylineOptionsModel.h"
#import "HQMapShowAreaOptionsModel.h"
#import "HQMapMarkerOptionsModel.h"
#import "HQMapMyLocationStyleModel.h"
#import "HQMapUiSettingsModel.h"
#import "HQMapPositionModel.h"
#import "HQMapStatusLimitsModel.h"
#import "UIColor+Hex.h"
#import "WeakProxy.h"

#import "CustomAnnotationView.h"


@interface HQMapManager() <UIGestureRecognizerDelegate, MAMapViewDelegate>

@property (nonatomic, strong) FlutterResult flutterResult;

/// 地图
@property (nonatomic, strong) MAMapView *mapView;

/// 工具类
@property (nonatomic, strong) HQMapTools * mapTools;

/// 路线options
@property (nonatomic, strong) HQMapPolylineOptionsModel *polylineOptionsModel;
/// 标记模型
@property (nonatomic, strong) HQMapMarkerOptionsModel *markerOptionsModel;
/// 定位模型
@property (nonatomic, strong) HQMapMyLocationStyleModel *locaiotnStyleModel;

@property (nonatomic, strong) NSObject<FlutterPluginRegistrar> *reg;
@property (nonatomic, strong) GdMapFlutterStreamHandler *streamHandler;


@end

@implementation HQMapManager 

+ (instancetype)shareInstance {
    static dispatch_once_t onceToken;
    static HQMapManager * manager = nil;
    dispatch_once(&onceToken, ^{
        manager = [[HQMapManager alloc] init];
    });
    return manager;
}

#pragma mark -- 插件方法

- (void)mapViewWithRegistrar:(NSObject<FlutterPluginRegistrar> *)registrar withMapPlugin:(NSObject<FlutterPlugin> * _Nonnull)mapPlugin viewIdentifier:(int64_t)viewId withMapView:(nonnull MAMapView *)mapV streamHandler:(GdMapFlutterStreamHandler * _Nullable)handler {
    
    self.reg = registrar;
    self.streamHandler = handler;

    /// 地图
    mapV.delegate = self;
    self.mapView = mapV;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    tap.delegate = self;
    [self.mapView addGestureRecognizer:tap];

    NSString *channelName = [NSString stringWithFormat:@"com.p595263720.com/map%lld", viewId];
    FlutterMethodChannel *mapChannel = [FlutterMethodChannel methodChannelWithName:channelName binaryMessenger:[registrar messenger]];
    [registrar addMethodCallDelegate:mapPlugin channel:mapChannel];
    NSString *receiveChannelName = [NSString stringWithFormat:@"com.p595263720.com/marker_clicked%lld", viewId];
    FlutterEventChannel *mapReceiveChannel = [FlutterEventChannel eventChannelWithName:receiveChannelName binaryMessenger:[registrar messenger]];
    [mapReceiveChannel setStreamHandler:handler];
}

- (void)mapViewMethodCall:(FlutterMethodCall *)call result:(FlutterResult)result {

//    NSLog(@"%@==%@", call.arguments, call.method);
    self.flutterResult = result;

    if([@"setMapType" isEqualToString:call.method]) {
        /// 设置地图模式
        [self setMapType: call];

    } else if([@"setZoomLevel" isEqualToString:call.method]) {
        /// 设置缩放等级 设置地图最大缩放级别 缩放级别范围为[3, 20],超出范围将按最大级别计算 。
        [self setZoomLevel: call];

    } else if([@"setPosition" isEqualToString:call.method]) {
        /// 设置中心点
        [self setPosition: call];

    } else if([@"changeLatLng" isEqualToString:call.method]) {
        /// 平移动到中心位置
        [self changeLatLng: call];

    } else if([@"getCenterPoint" isEqualToString:call.method]) {
        /// 获取中心点
        [self getCenterPoint: call];

    } else if([@"showIndoorMap" isEqualToString:call.method]) {
        /// 设置是否显示室内地图
        [self showIndoorMap: call];

    } else if([@"setUiSettings" isEqualToString:call.method]) {
        /// 设置地图初始化参数UiSetting
        [self setUiSettings: call];

    } else if([@"setMyLocationStyle" isEqualToString:call.method]) {
        /// 设置当前位置小图标
        [self setMyLocationStyle: call];

    } else if([@"addMarker" isEqualToString:call.method]) {
        /// 添加mark
        [self addMarker: call];

    } else if([@"addMarkers" isEqualToString:call.method]) {
        /// 添加marks  是应用与批量添加
        [self addMarkers: call];

    } else if([@"clearMarkers" isEqualToString:call.method]) {
        /// 清除可视区域内的所有mark点，参数为true,myLocationOverlay（内置定位覆盖物）除外。
        [self clearMarkers: call];

    } else if([@"clearMap" isEqualToString:call.method]) {
        /// 从地图上删除所有的覆盖物(marker，circle，polyline 等对象),参数为true,myLocationOverlay（内置定位覆盖物）除外。
        [self clearMap: call];

    } else if([@"addPolyline" isEqualToString:call.method]) {
        /// 添加线
        [self addPolyline: call];

    } else if([@"setPointToCenter" isEqualToString:call.method]) {
        /// 设置屏幕上的某个像素点为地图中心点
        [self setPointToCenter: call];

    } else if([@"setShowArea" isEqualToString:call.method]) {
        /// 设置最佳显示区域
        [self setShowArea: call];

    }

    ///---------------------- 未实现,需要联系作者开发区域(考虑到可能暂时不会使用) ------------------

    else if([@"map#setCustomMapStylePath" isEqualToString:call.method]) {
        /// 设置自定义样式的文件路径<离线调用>
        [self setCustomMapStylePath:call];

    } else if([@"map#setMapCustomEnable" isEqualToString:call.method]) {
        /// 是否开启自定义样式
        [self setMapCustomEnable:call];

    } else if([@"map#setCustomMapStyleID" isEqualToString:call.method]) {
        /// 使用在线自定义样式<在线调用>
        [self setCustomMapStyleID:call];

    } else if([@"map#setLanguage" isEqualToString:call.method]) {
        /// 设置语言
        [self setLanguage:call];

    } else if([@"map#zoomToSpan" isEqualToString:call.method]) {
        /// 移动镜头到当前的视角
        [self zoomToSpan:call];

    } else if([@"map#setMapStatusLimits" isEqualToString:call.method]) {
        /// 限制地图的显示范围
        [self setMapStatusLimits:call];

    }
}

#pragma mark -- 事件处理

- (void)setMapType:(FlutterMethodCall *)call {
    if (call.arguments) {
        int mayType = [call.arguments[@"mapType"] intValue];
        [self.mapView setMapType:mayType];
        self.flutterResult(NULL);
    }
}

- (void)setZoomLevel:(FlutterMethodCall *)call {
    if (call.arguments) {
        int level = [call.arguments[@"zoomLevel"] intValue];
        [self.mapView setZoomLevel:level];
        self.flutterResult(NULL);
    }
}

- (void)setPosition:(FlutterMethodCall *)call {
    NSString *position = call.arguments ? call.arguments : @"{}";
    HQMapPositionModel *positionModel = [HQMapPositionModel mj_objectWithKeyValues:position];
    if (positionModel) {
        [positionModel setPosition:self.mapView];
        self.flutterResult(NULL);
    }
}

- (void)changeLatLng:(FlutterMethodCall *)call {
    if (call.arguments) {
        NSString *latlng = call.arguments[@"target"];
        LatLngModel *model = [LatLngModel mj_objectWithKeyValues:latlng];
        [model changeLatLngWithMapView:self.mapView];
        self.flutterResult(NULL);
    }
}

- (void)getCenterPoint:(FlutterMethodCall *)call {
    CLLocationCoordinate2D center = [self.mapView centerCoordinate];
    LatLngModel *latLng = [LatLngModel initWithLat:center.latitude withLng:center.longitude];
    self.flutterResult([self.mapTools hq_jsonStringPrettyPrintedFormatForDictionary:[latLng mj_keyValues]]);
}

- (void)showIndoorMap:(FlutterMethodCall *)call {
    if (call.arguments) {
        BOOL enable = [call.arguments[@"showIndoorMap"] boolValue];
        self.mapView.showsIndoorMap = enable;
        self.flutterResult(NULL);
    }
}

- (void)setUiSettings:(FlutterMethodCall *)call {
    NSString *uiSettings = [self.mapTools isBlankString:call.arguments[@"uiSettings"]] ? call.arguments[@"uiSettings"] : @"{}";
    NSLog(@"uiSettings = %@", uiSettings);
    HQMapUiSettingsModel *settingsModel = [HQMapUiSettingsModel mj_objectWithKeyValues:uiSettings];
    if (settingsModel) {
        [settingsModel setUiSettings:self.mapView];
        self.flutterResult(NULL);
    }
}

- (void)setMyLocationStyle:(FlutterMethodCall *)call {
    NSString *myLocationStyle = [self.mapTools isBlankString:call.arguments[@"myLocationStyle"]] ? call.arguments[@"myLocationStyle"] : @"{}";
    self.locaiotnStyleModel = [HQMapMyLocationStyleModel mj_objectWithKeyValues:myLocationStyle];
    if (self.locaiotnStyleModel) {
        [self.locaiotnStyleModel setMyLocationStyle:self.mapView withFlutterRegistrar:self.reg];
        self.flutterResult(NULL);
    }
}

- (void)addMarker:(FlutterMethodCall *)call {
    self.mapView.delegate = self;
    NSString *markerOptions = [self.mapTools isBlankString:call.arguments[@"markerOptions"]] ? call.arguments[@"markerOptions"] : @"{}";
    NSLog(@"参数==%@",markerOptions);
    MarkerOptionsModel *markerOption = [MarkerOptionsModel mj_objectWithKeyValues:markerOptions];
    self.markerOptionsModel = [[HQMapMarkerOptionsModel alloc] init];
    self.markerOptionsModel.markerOptionsList = @[markerOption];
    NSArray<MarkerOptionsModel *> *optionsList = self.markerOptionsModel.markerOptionsList;
    if (optionsList) {
        [self.markerOptionsModel addMarker:self.mapView];
        self.flutterResult(NULL);
    }
}

- (void)addMarkers:(FlutterMethodCall *)call {
    self.mapView.delegate = self;
    self.markerOptionsModel = [HQMapMarkerOptionsModel createMarkerOptionsModelWithParams:call.arguments];
    if (self.markerOptionsModel) {
        [self.markerOptionsModel addMarkers:self.mapView];
        self.flutterResult(NULL);
    }
}

- (void)clearMarkers:(FlutterMethodCall *)call {
    /// 不再包含定位蓝点userLocation
    NSArray *anns = self.mapView.annotations;
    /// （内置定位覆盖物）除外
    BOOL isKeepMyLocationOverlay = call.arguments ? [call.arguments[@"isKeepMyLocationOverlay"] boolValue] : YES;
    for (id ann in anns) {
        [self.mapView removeAnnotation:ann];
    }
    /// 单独删除定位蓝点userLocation
    if (!isKeepMyLocationOverlay) {
        [self.mapView removeAnnotation:self.mapView.userLocation];
    }
    self.flutterResult(NULL);
}

- (void)clearMap:(FlutterMethodCall *)call {
    /// （内置定位覆盖物）除外
    BOOL isKeepMyLocationOverlay = call.arguments ? [call.arguments[@"isKeepMyLocationOverlay"] boolValue] : YES;
    [self.mapView removeOverlays:self.mapView.overlays];
    [self.mapView removeAnnotations:self.mapView.annotations];
    /// 单独删除定位蓝点userLocation
    if (!isKeepMyLocationOverlay) {
        [self.mapView removeAnnotation:self.mapView.userLocation];
    }
    self.flutterResult(NULL);
}

- (void)addPolyline:(FlutterMethodCall *)call {
    NSString *options = [self.mapTools isBlankString:call.arguments[@"options"]] ? call.arguments[@"options"] : @"{}";
    NSDictionary *dic = [self.mapTools parseJSONStringToNSDictionary:options];
    if (dic) {
        self.polylineOptionsModel = [HQMapPolylineOptionsModel mj_objectWithKeyValues:dic];
        [self.polylineOptionsModel addPolyline:self.mapView];
    }
    self.flutterResult(NULL);
}

- (void)setPointToCenter:(FlutterMethodCall *)call {
    double x = [call.arguments[@"x"] doubleValue];
    double y = [call.arguments[@"y"] doubleValue];
    MAMapPoint point = MAMapPointMake(x, y);
    CLLocationCoordinate2D pointCoordinate = MACoordinateForMapPoint(point);
    [self.mapView setCenterCoordinate:pointCoordinate animated:YES];
    self.flutterResult(NULL);
}

- (void)setShowArea:(FlutterMethodCall *)call {
    NSString *options = [self.mapTools isBlankString:call.arguments[@"options"]] ? call.arguments[@"options"] : @"{}";
    NSDictionary *dic = [self.mapTools parseJSONStringToNSDictionary:options];
    HQMapShowAreaOptionsModel *areaOptionsModel = [HQMapShowAreaOptionsModel mj_objectWithKeyValues:dic];
    if (areaOptionsModel) {
        [areaOptionsModel setShowArea:self.mapView];
        self.flutterResult(NULL);
    }
}

- (void)setCustomMapStylePath:(FlutterMethodCall *)call {
    if (call.arguments) {
        NSData *data = [self.mapTools getBundlePathWithName:call.arguments[@"path"]];
        MAMapCustomStyleOptions *options = [[MAMapCustomStyleOptions alloc] init];
        options.styleData = data;
        [self.mapView setCustomMapStyleOptions:options];
    }
}

- (void)setMapCustomEnable:(FlutterMethodCall *)call {
    if (call.arguments) {
        [self.mapView setCustomMapStyleEnabled:call.arguments[@"enabled"]];
    }
}

- (void)setCustomMapStyleID:(FlutterMethodCall *)call {
    if (call.arguments) {
        MAMapCustomStyleOptions *options = [[MAMapCustomStyleOptions alloc] init];
        options.styleId = call.arguments[@"styleId"];
        [self.mapView setCustomMapStyleOptions:options];
        self.mapView.customMapStyleEnabled = YES;
    }
}

- (void)setLanguage:(FlutterMethodCall *)call {
    if (call.arguments) {
        /// 0代表中文，1代表英文
        self.mapView.mapLanguage = @([call.arguments[@"language"] intValue]);
    }
}

- (void)zoomToSpan:(FlutterMethodCall *)call {
    if (call.arguments) {
    }
}

- (void)setMapStatusLimits:(FlutterMethodCall *)call {
    if (call.arguments) {
        HQMapStatusLimitsModel *limitsModel = [HQMapStatusLimitsModel mj_objectWithKeyValues:call.arguments];
        [limitsModel setMapStatusLimits:self.mapView];
    }
}

/// 获地图点击
- (void)tap:(UITapGestureRecognizer *)tap {
    CGPoint point = [tap locationInView:self.mapView];
    CLLocationCoordinate2D coor = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
    LatLngModel *latLng = [LatLngModel initWithLat:coor.latitude withLng:coor.longitude];
    NSString *jsonString = [self.mapTools hq_jsonStringPrettyPrintedFormatForDictionary:[latLng mj_keyValues]];
    NSLog(@"点击地图坐标：(%f, %f)===经纬度：%@", point.x, point.y, jsonString);
    NSLog(@"eventSink：%@", self.streamHandler.eventSink);
    if (self.streamHandler.eventSink) {
        self.streamHandler.eventSink(jsonString);
    }
}

#pragma mark -- 标记和绘制回调

/// 允许多个交互事件
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    return YES;
}

/// 解决点击地图和点marker冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if ([touch.view isKindOfClass:[MAAnnotationView class]]) { /// 点击 marker
        return NO;
    }
    return YES;
}

/// 绘制路线
- (MAOverlayRenderer *)mapView:(MAMapView *)mapView rendererForOverlay:(id <MAOverlay>)overlay {
    
    if ([overlay isKindOfClass:[MAPolyline class]]) {
        
        MAPolylineRenderer *polylineRenderer = [[MAPolylineRenderer alloc] initWithPolyline:overlay];
        polylineRenderer.lineWidth    = 6.0; // [self.polylineOptionsModel.width doubleValue]
        if (@available(iOS 11.0, *)) {
            polylineRenderer.fillColor    = [UIColor colorWithHexString:self.polylineOptionsModel.color];
        } else {
            /// Fallback on earlier versions
        }
        return polylineRenderer;
    }
    return nil;
}

/// 标记=自定义标记实现如下方法
- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id <MAAnnotation>)annotation {
    
    NSLog(@"== 大头针代理方法 ==");
    if ([annotation isKindOfClass:[MAUserLocation class]]) { /// 定位小蓝点
        NSLog(@"== 定位小蓝点 ==");
        static NSString *userLocationStyleReuseIndetifier = @"userLocationStyleReuseIndetifier";
        MAAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:userLocationStyleReuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:userLocationStyleReuseIndetifier];
        }

        UIImage *img = [self.mapTools getAppPluginImageWithPath:[self.mapTools getAppPluginImageWithRegistrar:self.reg withImageName:self.locaiotnStyleModel.myLocationIcon]];
        if (img) {
            annotationView.image = [self.mapTools scaleToSize:img size:CGSizeMake(72, 72)];
        } else {
            annotationView.image = [self.mapTools scaleToSize:[UIImage imageNamed:@"end"] size:CGSizeMake(72, 72)];
        }
        
//        MAUserLocationRepresentation *r = [[MAUserLocationRepresentation alloc] init];
//        r.showsAccuracyRing = NO;///精度圈是否显示，默认YES
//        r.showsHeadingIndicator = NO;///是否显示方向指示(MAUserTrackingModeFollowWithHeading模式开启)。默认为YES
//        r.fillColor = [UIColor redColor];///精度圈 填充颜色, 默认 kAccuracyCircleDefaultColor
//        r.strokeColor = [UIColor blueColor];///精度圈 边线颜色, 默认 kAccuracyCircleDefaultColor
//        r.lineWidth = 2;///精度圈 边线宽度，默认0
//        r.enablePulseAnnimation = NO;///内部蓝色圆点是否使用律动效果, 默认YES
//        r.locationDotBgColor = [UIColor greenColor];///定位点背景色，不设置默认白色
//        r.locationDotFillColor = [UIColor grayColor];///定位点蓝色圆点颜色，不设置默认蓝色
////        r.image = [UIImage imageNamed:@"你的图片"]; ///定位图标, 与蓝色原点互斥
//        [self.mapView updateUserLocationRepresentation:r];
        
        return annotationView;
        
    }
    
    /// 默认大头针
//    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
//        NSLog(@"默认大头针");
//        NSString *pointReuseIndetifier = @"myReuseIndetifier";
//        MAPinAnnotationView *annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
//        if (annotationView == nil) {
//            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation
//                                                             reuseIdentifier:pointReuseIndetifier];
//        }
//        annotationView.selected = YES;
//        /// 设置气泡可以弹出，默认为NO
//        annotationView.canShowCallout = YES;
//        /// 设置标注动画显示，默认为NO
//        annotationView.animatesDrop = YES;
//        /// 设置标注可以拖动，默认为NO
//        annotationView.draggable = YES;
//        annotationView.pinColor = MAPinAnnotationColorPurple;
//
//        return annotationView;
//    }
    
    /// 自定大头针和气泡
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        NSLog(@"== 自定义大头针 ==");
        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
        MAAnnotationView *annotationView = (MAAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
        if (annotationView == nil) {
            annotationView = [[MAAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
        }

        /// infoWindowFlag：1 车主接单显示callout。2 货主发货显示callout
        MAPointAnnotation *pointAnnotation = annotation;
        MarkerOptionsModel *opModel = self.markerOptionsModel.markerOptionsList[[pointAnnotation.title intValue]];
//        NSLog(@"opModel = %@", opModel);
        if (opModel) {
            /// 设置为NO，用以调用自定义的calloutView
            annotationView.canShowCallout = opModel.infoWindowEnable;
            /// 设置是否处于选中状态, 外部如果要选中请使用mapView的selectAnnotation方法
            annotationView.selected = opModel.infoWindowEnable;
            /// 设置标注可以拖动，默认为NO
            annotationView.draggable = opModel.draggable;
//            if (opModel.infoWindowEnable) {
//                /// 设置callout内容
//                annotationView.calloutView.title = [NSString stringWithFormat:@"预估运费%@", opModel.title];
//                annotationView.calloutView.subtitle = [NSString stringWithFormat:@"全程%@公里，约行驶%@小时", opModel.snippet, opModel.extData.dic_time];
//            }
            /// 设置大头针图片
            UIImage *img = [self.mapTools getAppPluginImageWithPath:[self.mapTools getAppPluginImageWithRegistrar:self.reg withImageName:[opModel icon]]];
            if (img) {
                annotationView.image = [self.mapTools scaleToSize:img size:CGSizeMake(72, 72)];
            } else {
                annotationView.image = [self.mapTools scaleToSize:[UIImage imageNamed:@"end"] size:CGSizeMake(72, 72)];
            }
        }
        /// 设置中心点偏移，使得标注底部中间点成为经纬度对应点
        annotationView.centerOffset = CGPointMake(0, -18);

        return annotationView;
    }
    
//    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
//        NSLog(@"== 自定义大头针 ==");
//        static NSString *reuseIndetifier = @"annotationReuseIndetifier";
//        CustomAnnotationView *annotationView = (CustomAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:reuseIndetifier];
//        if (annotationView == nil) {
//            annotationView = [[CustomAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:reuseIndetifier];
//        }
//
//        /// infoWindowFlag：1 车主接单显示callout。2 货主发货显示callout
//        MAPointAnnotation *pointAnnotation = annotation;
//        MarkerOptionsModel *opModel = self.markerOptionsModel.markerOptionsList[[pointAnnotation.title intValue]];
//        NSLog(@"opModel = %@", opModel);
//        if (opModel) {
//            /// 设置为NO，用以调用自定义的calloutView
//            annotationView.canShowCallout = opModel.infoWindowEnable;
//            /// 设置是否处于选中状态, 外部如果要选中请使用mapView的selectAnnotation方法
//            annotationView.selected = opModel.infoWindowEnable;
//            /// 设置标注可以拖动，默认为NO
//            annotationView.draggable = opModel.draggable;
//            if (opModel.infoWindowEnable) {
//                /// 设置callout内容
//                annotationView.calloutView.title = [NSString stringWithFormat:@"预估运费%@", opModel.title];
//                annotationView.calloutView.subtitle = [NSString stringWithFormat:@"全程%@公里，约行驶%@小时", opModel.snippet, opModel.extData.dic_time];
//            }
//            /// 设置大头针图片
//            UIImage *img = [self.mapTools getAppPluginImageWithPath:[self.mapTools getAppPluginImageWithRegistrar:self.reg withImageName:[opModel icon]]];
//            if (img) {
//                annotationView.image = [self.mapTools scaleToSize:img size:CGSizeMake(72, 72)];
//            } else {
//                annotationView.image = [self.mapTools scaleToSize:[UIImage imageNamed:@"end"] size:CGSizeMake(72, 72)];
//            }
//        }
//        /// 设置中心点偏移，使得标注底部中间点成为经纬度对应点
//        annotationView.centerOffset = CGPointMake(0, -18);
//
//        return annotationView;
//    }

    return nil;
}

/// 添加完大头针的代理方法<自动弹出气泡>
- (void)mapView:(MAMapView *)mapView didAddAnnotationViews:(NSArray *)views {
    [self.markerOptionsModel.markerOptionsList enumerateObjectsUsingBlock:^(MarkerOptionsModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if (obj.infoWindowEnable) {
            if ([views[idx] isKindOfClass:MAPinAnnotationView.class]) {
                MAPinAnnotationView *mapView = (MAPinAnnotationView*)views[idx];
                [self.mapView selectAnnotation:mapView.annotation animated:true];
            }
        }
    }];
}

/// 点击marker 返回 mark 数据（原生发命令反RN-监听）
- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    NSLog(@"点击marker");
    MAPointAnnotation *annotaion = (MAPointAnnotation *)view.annotation;
    LatLngModel *latLng = [LatLngModel initWithLat:annotaion.coordinate.latitude withLng:annotaion.coordinate.longitude];
    NSString *jsonString = [self.mapTools hq_jsonStringPrettyPrintedFormatForDictionary:[latLng mj_keyValues]];
    NSLog(@"marker经纬度：%@", jsonString);
    NSLog(@"eventSink：%@", self.streamHandler.eventSink);
    if (self.streamHandler.eventSink) {
        self.streamHandler.eventSink(jsonString);
    }
}

/// 取消点击marker
- (void)mapView:(MAMapView *)mapView didDeselectAnnotationView:(MAAnnotationView *)view {
    NSLog(@"取消点击marker");
}

/**
 要在iOS 11及以上版本使用后台定位服务, 需要实现amapLocationManager:doRequireLocationAuth: 代理方法
 当plist配置NSLocationAlwaysUsageDescription或者NSLocationAlwaysAndWhenInUseUsageDescription，并且[CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined，会调用代理的此方法。
      此方法实现调用申请后台权限API即可：[locationManager requestAlwaysAuthorization](必须调用,不然无法正常获取定位权限)
 */
- (void)mapViewRequireLocationAuth:(CLLocationManager *)locationManager {
    [locationManager requestAlwaysAuthorization];
}

#pragma mark -- 懒加载

- (HQMapTools *)mapTools {
    if (!_mapTools) {
        _mapTools = [HQMapTools shareInstance];
    }
    return _mapTools;
}

@end
